#!/usr/bin/env bash

# Copyright 2020 The Ckeadm Authors.
#
# Use this in cke-deploy images, to scale or scale-down nodes,
# installing addons and stroage.
#
# usage:
# /bin/playbook scale --config "-----configration---------sha256-----------here-------------"
# /bin/playbook uninstall --config "-----configration---------sha256-----------here-------------"
# /bin/playbook patch --config "-----configration---------sha256-----------here-------------"

set -o errexit
set -o pipefail
#set -o nounset

usage()
{
    cat << EOF
use for scale nodes and scale down node, run parch

Usage : $(basename $0) [scale/uninstall/patch] --execyml <ymlfile> --before <shell> --config <config> --fork <fork> --logpath <logpath> --logname <filename>
      --config       : configration context as string
      --execyml      : ansible ymlfile should execed
      --fork         : fork number of ansible
      --before       : exec before run command
      --wait         : wait time before exec command
      --logpath      : logpath is a dir for logs
      --logname      : logname is log file name
EOF
}

logdir=/var/log/ckelogs
logfile=ckeadmlog

fork=5
CommandBefore=()

ymlfile=""
exitcode=0

# Options parsing
while (($#)); do
    case "$1" in
        -h | --help)
            usage
            exit 0
            ;;
        scale | uninstall | patch)
            command=$1
            shift 1
            ;;
        --execyml)
            ymlfile=$2
            shift 2
            ;;
        --config)
            echo ${2} | base64 -d > /opt/cluster.yml
            shift 2
            ;;
        --fork)
            fork=$2
            shift 2
            ;;
        --before)
            CommandBefore+=("$2")
            shift 2
            ;;
        --logpath)
            logdir=$2
            shift 2
            ;;
        --logname)
            logfile=$2
            shift 2
            ;;
        --wait)
            WaitTime=$2
            shift 2
            ;;
        *)
            usage
            echo "ERROR : Unknown option"
            exit 3
        ;;
    esac
done

# fix: jian rong lao de ban ben
case $command in
  scale)
    ymlfile='scale.yml'
    ;;
  uninstall)
    ymlfile='scale_down.yml'
    ;;
  patch)
    ymlfile='patch.yml'
    ;;
esac

if [[ x$ymlfile == x"" ]]; then
  echo "ERROR : Unknown Exec Ansible Yaml"
  exit 4
fi

for commandbefore in "${CommandBefore[@]}"; do
  $commandbefore
done

ansibleArgs="-i /opt/kubernetes-deploy/my_inventory/my_inventory.cfg -b -v --private-key=~/.ssh/id_rsa -f $fork -T 300"


### genssis config file under /opt/kubernetes-deploy/my_inventory/
ckeadm transform -f /opt/cluster.yml

if [[ $WaitTime != "" ]]; then
  sleep $WaitTime
fi

# mkdir log dir for logs
mkdir -p $logdir
logfile=$logfile.`date '+%Y-%m-%d@%H:%M:%S'`.log

# scale scale_down patch
ansible-playbook /opt/kubernetes-deploy/${ymlfile} ${ansibleArgs} 2>&1 | tee ${logdir}/${logfile}
exit ${PIPESTATUS[0]}